import AppConfig from '@/config';
import { API_CODES, isApiSuccess, useErrorHandler } from './errorHandler.js';

/**
 * API客户端类
 */
export class ApiClient {
    constructor(baseURL = '') {
        this.baseURL = baseURL || AppConfig.api.baseURL;
        this.timeout = AppConfig.api.timeout;
        this.retryCount = AppConfig.api.retryCount;
        this.errorHandler = useErrorHandler();
        this.defaultHeaders = {
            'Content-Type': 'application/json'
        };
    }

    /**
     * 获取认证头
     * @returns {Object}
     */
    getAuthHeaders() {
        const token = localStorage.getItem('Authorization');
        return token ? { 'Authorization': token } : {};
    }

    /**
     * 构建完整的URL
     * @param {string} endpoint - API端点
     * @returns {string}
     */
    buildURL(endpoint) {
        return `${this.baseURL}${endpoint}`;
    }

    /**
     * 请求拦截器
     * @param {Object} config - 请求配置
     * @returns {Object}
     */
    requestInterceptor(config) {
        // 添加认证头
        const authHeaders = this.getAuthHeaders();
        config.headers = {
            ...this.defaultHeaders,
            ...authHeaders,
            ...config.headers
        };

        // 添加超时控制
        config.signal = AbortSignal.timeout(this.timeout);

        // 记录请求日志(开发环境)
        if (process.env.NODE_ENV === 'development') {
            console.log('[API Request]', config);
        }

        return config;
    }

    /**
     * 重试机制
     * @param {Function} requestFn - 请求函数
     * @param {number} retries - 重试次数
     * @param {number} delay - 延迟时间
     * @returns {Promise}
     */
    async retryRequest(requestFn, retries = this.retryCount, delay = 1000) {
        try {
            return await requestFn();
        } catch (error) {
            if (retries > 0 && this.shouldRetry(error)) {
                console.log(`Request failed, retrying in ${delay}ms... (${retries} retries left)`);
                await new Promise(resolve => setTimeout(resolve, delay));
                return this.retryRequest(requestFn, retries - 1, delay * 2);
            }
            throw error;
        }
    }

    /**
     * 判断是否应该重试
     * @param {Error} error - 错误对象
     * @returns {boolean}
     */
    shouldRetry(error) {
        // 网络错误或5xx错误才重试
        return error.name === 'NetworkError' ||
               (error.status >= 500 && error.status < 600) ||
               error.name === 'TimeoutError';
    }

    /**
     * 响应拦截器
     * @param {Response} response - 响应对象
     * @returns {Promise}
     */
    async responseInterceptor(response) {
        try {
            const data = await response.json();

            // 记录响应日志(开发环境)
            if (process.env.NODE_ENV === 'development') {
                console.log('[API Response]', data);
            }
            // 处理业务错误
            if (!isApiSuccess(data)) {
                // 处理令牌过期或需要重新登录的情况
                if (data.Code === API_CODES.UNAUTHORIZED || data.Code === API_CODES.TOKEN_EXPIRED) {
                    // 处理未授权错误
                    localStorage.removeItem('Authorization');
                    window.location.href = '/auth/login';
                    return Promise.reject(new Error('未授权访问'));
                }
                this.errorHandler.handleApiError(data);
                return Promise.reject(data);
            }

            return data;
        } catch (error) {
            // 处理JSON解析错误
            this.errorHandler.handleNetworkError(error, 'JSON解析失败');
            return Promise.reject(error);
        }
    }

    /**
     * 通用请求方法
     * @param {string} endpoint - API端点
     * @param {Object} options - 请求选项
     * @returns {Promise}
     */
    async request(endpoint, options = {}) {
        const url = this.buildURL(endpoint);
        const config = this.requestInterceptor({
            method: 'GET',
            headers: {},
            ...options
        });

        const requestFn = async () => {
            const response = await fetch(url, config);

            if (!response.ok) {
                const error = new Error(`HTTP error! status: ${response.status}`);
                error.status = response.status;
                throw error;
            }

            return await this.responseInterceptor(response);
        };

        return this.retryRequest(requestFn);
    }

    /**
     * GET请求
     * @param {string} endpoint - API端点
     * @param {Object} params - 查询参数
     * @returns {Promise}
     */
    async get(endpoint, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const url = queryString ? `${endpoint}?${queryString}` : endpoint;

        return this.request(url, {
            method: 'GET'
        });
    }

    /**
     * POST请求
     * @param {string} endpoint - API端点
     * @param {Object} data - 请求数据
     * @returns {Promise}
     */
    async post(endpoint, data = {}) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    /**
     * PUT请求
     * @param {string} endpoint - API端点
     * @param {Object} data - 请求数据
     * @returns {Promise}
     */
    async put(endpoint, data = {}) {
        return this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    /**
     * DELETE请求
     * @param {string} endpoint - API端点
     * @returns {Promise}
     */
    async delete(endpoint) {
        return this.request(endpoint, {
            method: 'DELETE'
        });
    }

    /**
     * 文件上传请求
     * @param {string} endpoint - API端点
     * @param {FormData} formData - 表单数据
     * @returns {Promise}
     */
    async upload(endpoint, formData) {
        const config = this.requestInterceptor({
            method: 'POST',
            headers: {}, // 不设置Content-Type，让浏览器自动设置
            body: formData
        });

        // 移除Content-Type，让浏览器处理multipart/form-data
        delete config.headers['Content-Type'];

        const requestFn = async () => {
            const response = await fetch(this.buildURL(endpoint), config);

            if (!response.ok) {
                const error = new Error(`HTTP error! status: ${response.status}`);
                error.status = response.status;
                throw error;
            }

            return await this.responseInterceptor(response);
        };

        return this.retryRequest(requestFn);
    }
}

// 创建API客户端实例（不带缓存）
export const apiClient = new ApiClient();

// 导出基础API客户端实例（别名）
export const baseClient = new ApiClient();
